package com.froggyware.tadpole.query;

import com.froggyware.tadpole.TadObject;
import com.froggyware.tadpole.core.TadpoleException;

import java.lang.reflect.Field;

/**
 * Created by IntelliJ IDEA.
 * User: mst
 * Date: Sep 5, 2011
 * Time: 5:42:14 PM
 * To change this template use File | Settings | File Templates.
 */
public class RegexSelector implements Selector {

    private String fieldName;
    private String regex;

    public RegexSelector(String fieldName, String regex) {
        this.fieldName = fieldName;
        this.regex = regex;
    }

    @Override
    public boolean select(TadObject entity) {
        try {
            Field f = entity.getClass().getField(fieldName);
            Object val = f.get(entity);
            if (val != null) {
                String strVal = val.toString();
                return strVal.matches(regex);
            }
            return false;
        } catch (Exception e) {
            throw new TadpoleException("selector failed on field " + fieldName + " with class" + entity.getClass(), e);
        }
    }
}
